650. 2 Keys Keyboard
650. 2 Keys Keyboard
Description
Solution
O(n^2), search from 1 to i-1 to find the smallest operation number for dp[i]
O(sqrt(n)), all the operations sequences are like :
CPPPCPPPPCP...
, can be divided into groups (CPPP)(CPP)(CP)…. .If we have each group’s length likeg1, g2,g3...
, so after first group, there areg1
A’s, after second groupg1 * g2
A’s…We want have
N = g1 * g2 * g3...*gn
A’s, ifgi
can be divided into product of other two numbers, denote asgi = p * q
, so it can be divided into 2 group, first contains 1C
and p-1P
, second one contains 1C
and q-1P
. It is easy to prove that after dividing, we need fewer steps.
Code
1 | class Solution { |
1 |
|
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.